// pages/exam/exam.js
const app = getApp()
const util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    expireTime:true,
    userInfo: null,
    //题型
    curOptionTypeName: '选择题',
    curOptionTypeId: 'all',
    optionType: [
      // all,radio,multiple,judge 
      {
        id: 'radio',
        name: '单选题'
      },
      {
        id: 'multiple',
        name: '多选题'
      },
      {
        id: 'judge',
        name: '判断题'
      },
      {
        id: 'all',
        name: '全部'
      }
    ],
    currentPage: 1, //当前页数
    doneExerciseList: [],
    options: {}, //章节类型
    exerciseCount: 0,
    exerciseList: [], //试题列表
    currentExercise: null,
    currentIndex: 0, //当前试题下表
    isCollect: false, //收藏
    isCloseAnalyse: true, //打开解析
    userSelectAnswer: "",
    arrUserSelectAnswer: [],
    rightNumber: 0,
    errorNumber: 0,
    optionItem: {
      A: {
        select: false,
        color: 'text-white'
      },
      B: {
        select: false,
        color: 'text-white'
      },
      C: {
        select: false,
        color: 'text-white'
      },
      D: {
        select: false,
        color: 'text-white'
      },
    },
    startX: 0, //滑动开始x轴位置
    startY: 0, //滑动开始y轴位置
    allSelectData: {}, //记录用户选择数据
    screenHeight: 0, //屏幕的高度
  },
  /**
   * 用户选择
   */
  userSlectAnswerTap: function (res) {
    console.log(res)
    var userSelect = res.currentTarget.dataset.optionId;
    var optionItem;
    if (this.data.currentExercise.optionType == "multiple") {
      optionItem = this.data.optionItem;
    } else {
      optionItem = this.getInitOptionItem()
    }
    if (optionItem[userSelect].select) {
      optionItem[userSelect].color = 'text-white'
      optionItem[userSelect].select = false
    } else {
      optionItem[userSelect].color = 'bg-green'
      optionItem[userSelect].select = true
    }
    console.log(optionItem)
    this.setData({
      optionItem: optionItem
    })
  },
  getUserSelectData: function () {
    var optionItem = this.data.optionItem
    var selectData = '';
    if (optionItem.A.select) {
      if (selectData == '') {
        selectData = 'A'
      } else {
        selectData = selectData + ',' + 'A'
      }
    }
    if (optionItem.B.select) {
      if (selectData == '') {
        selectData = 'B'
      } else {
        selectData = selectData + ',' + 'B'
      }
    }
    if (optionItem.C.select) {
      if (selectData == '') {
        selectData = 'C'
      } else {
        selectData = selectData + ',' + 'C'
      }
    }
    if (optionItem.D.select) {
      if (selectData == '') {
        selectData = 'D'
      } else {
        selectData = selectData + ',' + 'D'
      }
    }
    return selectData
  },
  getInitRifhtOptionItem: function (arrData) {
    var optionItem = this.getInitOptionItem()
    console.log(optionItem)
    for (var i = 0; i < arrData.length; i++) {
      optionItem[arrData[i]].color = 'bg-green'
    }
    return optionItem
  },
  submitAnswerTap: function () {
    // console.log()
    var errorNumber = this.data.errorNumber
    var rightNumber = this.data.rightNumber
    var right = true
    var rightAnswer = this.data.currentExercise.rightAnswer.split(',')
    var optionItem = this.getInitRifhtOptionItem(rightAnswer)
    var allUserSelectData = this.getUserSelectData().split(',')
    console.log("--------------------")
    console.log(allUserSelectData)
    if(allUserSelectData[0]==""){
      return
    }
    var flag = 0
    for (var i = 0; i < allUserSelectData.length; i++) {
      if (optionItem[allUserSelectData[i]].color == 'bg-green') {
        flag++
      } else {
        optionItem[allUserSelectData[i]].color = 'bg-red'
      }
    }
    if (rightAnswer.length == flag) {
      rightNumber++
      right = true
    } else {
      errorNumber++
      right = false
    }
    var allSelectData = this.data.allSelectData
    allSelectData[this.data.currentExercise.exerciseId] = this.getUserSelectData()
    this.setData({
      userSelectAnswer: this.getUserSelectData(),
      optionItem: optionItem,
      errorNumber: errorNumber,
      rightNumber: rightNumber
    })
    //提交
    var url = "exercise/do"
    var data = {
      userId: this.data.userInfo.userId,
      exerciseId: this.data.currentExercise.exerciseId,
      chapterId: this.data.currentExercise.chapterId,
      right: right
    }
    util.postHttp(url, data, this.exerciseDo_callBack)
  },
  exerciseDo_callBack: function (res) {
    console.log("记录做题的序号"+this.data.currentIndex)
    //只有在curOptionTypeId 题型为all的时候才会记录
    if(this.data.curOptionTypeId == "all"){
      ///章节id
      var chapterId = this.data.options.chapterId
      var exeRec = wx.getStorageSync("exeRec")||{}
      var recData = exeRec[chapterId]||{}
      recData["currentPage"] = this.data.currentPage
      recData["currentIndex"] = this.data.currentIndex+1
      if(this.data.currentIndex == 19){
        recData["currentIndex"] = 0
        recData["currentPage"] = this.data.currentPage + 1
      }
      
      exeRec[chapterId]=recData
      wx.setStorageSync('exeRec',exeRec)
      console.log(exeRec)
    }else{
      console.log("记录做题的序号 not all"+this.data.curOptionTypeId )
    }
    
  },
  /**
    题型选择
  */
 getcurOptionTypeName:function(curOptionTypeId){
  var optionType = this.data.optionType;
  for (var i = 0; i < optionType.length; i++) {
    if (optionType[i].id == curOptionTypeId) {
      return optionType[i].name;
    }
  }
  return "选择题"
 },
  optionTypeChange: function (e) {

    var curOptionTypeName = this.getcurOptionTypeName(this.data.currentExercise.optionType);
    this.setData({
      curOptionTypeId: e.detail.value,
      curOptionTypeName: curOptionTypeName,
      currentIndex:0,
      isCloseAnalyse: !this.data.isCloseAnalyse
    });
    this.getExerciseList(0)
  },
  /**
   * 收藏
   */
  collectTap: function (res) {
    var url = "collection/change"
    var data = {
      userId: this.data.userInfo.userId,
      exerciseId: this.data.currentExercise.exerciseId,
      chapterId: this.data.currentExercise.chapterId
    }
    util.postHttp(url, data, this.collect_callBack)
  },
  collect_callBack: function (res) {
    console.log(res)
    this.setData({
      isCollect: !this.data.isCollect
    })
  },
  /**
   * 打开解析
   */
  openAnalyseTap: function () {
    this.setData({
      isCloseAnalyse: !this.data.isCloseAnalyse
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    //练习
    this.setData({
      userInfo: wx.getStorageSync("userInfo") || "",
      options:options,
      screenHeight: wx.getSystemInfoSync().windowHeight, // 获取屏幕的高
      screenWidth: wx.getSystemInfoSync().windowWidth
    })

    //判断练习时长
    var nowtime = new Date(), //获取当前时间
      endtime = new Date(this.data.userInfo.expireTime); //定义结束时间
    var lefttime = endtime.getTime() - nowtime.getTime(); //距离结束时间的毫秒数
    console.log(lefttime)
    if(lefttime<0){
      wx.showModal({
        title: '提示',
        content: "您的练题权限已经到期，请与启程教育联系，从新获得权限。", 
        showCancel: false,
        success (res) {
          if (res.confirm) {
            wx.switchTab({
              url:'../course/course'
            })
          } 
        }
      })
    }else{

      var chapterId = this.data.options.chapterId
      var exeRec = wx.getStorageSync("exeRec")||{}
      var recData = exeRec[chapterId]||{}
      var currentPage = recData["currentPage"]||1
      var currentIndex = recData["currentIndex"]||0
      this.setData({
        currentPage:currentPage,
        currentIndex:currentIndex
      })
      var beginPage = (currentPage-1)*20
      console.log("gsahddgasasdj"+beginPage)
      
      this.getExerciseList(beginPage)
    }

  },
  getExerciseList: function (beginPage) {
    var url;
    var data;
    console.log(this.data.options.searchType)
    if (this.data.options.searchType == "everyday") {
      url = "exercise/day"
      data = {
        exerDate: this.data.options.exerdate
      }
    }else if(this.data.options.searchType == "collection" || this.data.options.searchType == "error"){
      url = "exercise/list"
      data = {
        userId: this.data.userInfo.userId, //用户id
        optionType: this.data.curOptionTypeId, // 题型
        chapterId: this.data.options.chapterId, //章节id
        subjectType: this.data.options.subjectType, //科目类型
        pageBegin: beginPage,
        pageSize: 20,
        searchType:this.data.options.searchType //查询方式
      }
    }else if(this.data.options.searchType == "default"){
      //提交
      url = "exercise/list"
      data = {
        userId: this.data.userInfo.userId, //用户id
        optionType: this.data.curOptionTypeId, // 题型
        chapterId: this.data.options.chapterId, //章节id
        subjectType: this.data.options.subjectType, //科目类型
        pageBegin: beginPage,
        pageSize: 20
      }
    }
    console.log("练习题"+beginPage)
    console.log(data)
    util.postHttp(url, data, this.getExerciseList_callBack)

  },
  getExerciseList_callBack: function (res) {
    var exerciseList = res.data.exerciseList
    
    var currentIndex = this.data.currentIndex
    if(currentIndex<0 || currentIndex>=exerciseList.length){
      currentIndex=0
    }

    var optionItem = this.getInitOptionItem()
    
    var curOptionTypeName = this.getcurOptionTypeName(exerciseList[currentIndex].optionType);
  
    this.setData({
      expireTime:false,
      optionItem: optionItem,
      userSelectAnswer: "",
      curOptionTypeName:curOptionTypeName,
      // curOptionTypeId:exerciseList[0].optionType,
      allSelectData: {}, //用户做题为空
      exerciseList: exerciseList,
      currentExercise: exerciseList[currentIndex],
      isCollect: exerciseList[currentIndex].collect,
      exerciseCount: res.data.count
    })

    console.log(this.data.exerciseList)
  },
  //开始滑动事件
  touchStart: function (res) {
    this.setData({
      startX: res.changedTouches[0].clientX,
      startY: res.changedTouches[0].clientY
    })
  },
  // 结束滑动
  touchEnd: function (res) {
    var endX = res.changedTouches[0].clientX
    var endY = res.changedTouches[0].clientY
    var startX = this.data.startX
    var startY = this.data.startY
    var currentIndex
    // 判断左右滑动
    if (endX - startX > 50 && Math.abs(endY - startY) < 50) {
      currentIndex = this.data.currentIndex - 1
      this.getNextQuestion(currentIndex)
    } else if (endX - startX < -50 && Math.abs(endY - startY) < 50) {
      currentIndex = this.data.currentIndex + 1
      this.getNextQuestion(currentIndex)
    }

  },
  getNextQuestion: function (currentIndex) {

    var currentIndex = currentIndex

    if (currentIndex >= 0 && currentIndex < this.data.exerciseList.length) {
      // 当前的练习
      var currentExercise = this.data.exerciseList[currentIndex]
      // 判断是否做过
      var userSelectAnswer = this.data.allSelectData[currentExercise.exerciseId] || ''
      var optionItem = this.getInitOptionItem()

      if (userSelectAnswer) {

        var rightAnswer = this.data.currentExercise.rightAnswer.split(',')
        var optionItem = this.getInitRifhtOptionItem(rightAnswer)
        var allUserSelectData = userSelectAnswer.split(',')
        for (var i = 0; i < allUserSelectData.length; i++) {
          if (optionItem[allUserSelectData[i]].color == 'bg-green') {} else {
            optionItem[allUserSelectData[i]].color = 'bg-red'
          }
        }
      }
      var curOptionTypeName = this.getcurOptionTypeName(currentExercise.optionType);
      this.setData({
        currentExercise: currentExercise,
        curOptionTypeName:curOptionTypeName,
        // curOptionTypeId:currentExercise.optionType,
        currentIndex: currentIndex,
        isCollect: currentExercise.collect,
        isCloseAnalyse: true,
        userSelectAnswer: userSelectAnswer,
        optionItem: optionItem,
      })

    } else {
      wx.showToast({
        title: "换个方向试试，可能会有惊喜哦。",
        icon: "none",
        duration: 1500
      })
    }
  },
  //模态框显示和隐藏
  showModalTap: function (res) {
    this.setData({
      modalName: res.currentTarget.dataset.modelame
    })
  },
  hideModal() {
    this.setData({
      modalName: null
    })
  },
  //页码选择
  setPageTap: function (res) {
    console.log(res)
    var currentPage = res.currentTarget.dataset.page
    var beginPage = (currentPage - 1) * 20
    this.getExerciseList(beginPage)
    this.setData({
      currentPage: currentPage,
      modalName: null,
      currentIndex: 0,
      isCloseAnalyse: !this.data.isCloseAnalyse
    })

  },
  getInitOptionItem: function () {
    return {
      A: {
        select: false,
        color: 'text-white'
      },
      B: {
        select: false,
        color: 'text-white'
      },
      C: {
        select: false,
        color: 'text-white'
      },
      D: {
        select: false,
        color: 'text-white'
      },
    };
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})